package guoanmaker.operator.business.service;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.model.OperatorGuarantee;
import guoanmaker.operator.business.model.OperatorUser;
import guoanmaker.operator.business.modelnobind.OperatorCitiesMove;
import guoanmaker.operator.business.repository.OperatorGuaranteeRepository;

@Service
public class OperatorGuaranteeService implements OperatorGuaranteeServiceInterface {

	@PersistenceContext
	private EntityManager manager;

	
	@Autowired
	private OperatorGuaranteeRepository operatorGuaranteeRepository;
	
	public OperatorGuarantee getOperatorGuarantee() {
		List<OperatorGuarantee> list= operatorGuaranteeRepository.findAll();
		if(list!=null&&list.size()>0){
			return list.get(0);
		}
		return null;
	}

	public OperatorGuarantee insertOrEdit(String id, String guarantee, String userid) {
		if(id!=null&&id.length()>0){
			String jpql="update OperatorGuarantee o set o.guarantee=:guarantee,o.updateTime=:updateTime where o.id=:id";
	    	Query query=manager.createQuery(jpql).setParameter("guarantee", guarantee).setParameter("updateTime", new Date()).setParameter("id", id);
	    	query.executeUpdate();
	    	OperatorGuarantee operatorGuarantee=new OperatorGuarantee();
			operatorGuarantee.setId(id);
	    	return operatorGuarantee;
		}else{
			OperatorGuarantee operatorGuarantee=new OperatorGuarantee();
			operatorGuarantee.setCreateTime(new Date());
			operatorGuarantee.setGuarantee(guarantee);
			operatorGuarantee.setUpdateTime(new Date());
			OperatorUser operatorUser=new OperatorUser();
			operatorUser.setId(userid);
			operatorGuarantee.setOperatorUser(operatorUser);
			return operatorGuaranteeRepository.save(operatorGuarantee);
		}
		
	}

	
}
